﻿#include "Base_MessageQueue.h"
#include "Base_Monitor.h"
#include "Log.h"

Base_GlobalQueue::Base_GlobalQueue()
	:m_queue(new std::queue<Base_MessageQueue*>())
	,m_monitor(Base_Monitor::get_instance())
{
	
}

Base_GlobalQueue::~Base_GlobalQueue()
{

}

Base_GlobalQueue * Base_GlobalQueue::get_global_queue_instance()
{
	static Base_GlobalQueue b;
	return &b;
}

void Base_GlobalQueue::global_queue_push(Base_MessageQueue* mq)
{
	std::lock_guard<std::mutex> m{ m_mutex };
	m_queue->push(mq);
	mq->set_in_gmq_flag(true);
}

Base_MessageQueue* Base_GlobalQueue::global_queue_pop()
{
	std::lock_guard<std::mutex> m{ m_mutex };
	if (m_queue->size()>0)
	{
		auto q=m_queue->front();
		q->set_in_gmq_flag(false);
		m_queue->pop();
		return q;
	}
	DEBUG("返回空的消息队列\n");
	return nullptr;
}


Base_MessageQueue::Base_MessageQueue(uint32_t handle, Base_Context * context)
	:m_handle(handle), m_queue(new std::queue<Base_Message>()),m_context(context)
	,m_inGmq(false)
{

}

Base_MessageQueue::~Base_MessageQueue()
{

}

void Base_MessageQueue::mq_push(const Base_Message& msg)
{
	{
		std::lock_guard<std::mutex> m{ this->m_mutex_queue };
		m_queue->push(msg);
	}
	if (this->get_in_gmq_flag())
	{
		return;
	}
	Base_GlobalQueue::get_global_queue_instance()->global_queue_push(this);
}

int Base_MessageQueue::mq_pop(Base_Message & msg)
{
	std::lock_guard<std::mutex> m{ m_mutex_queue };
	int s = m_queue->size();
	if (s>0)
	{
		msg = m_queue->front();
		m_queue->pop();
		s = s - 1;
		return s;
	}
	return 0;
}

Base_Context * Base_MessageQueue::get_context() const
{
	return m_context;
}

inline void Base_MessageQueue::set_in_gmq_flag(bool in)
{
	std::lock_guard<std::mutex> {m_mutex_in_gmq_state};
	m_inGmq = in;
}

bool Base_MessageQueue::get_in_gmq_flag()
{
	std::lock_guard<std::mutex> {m_mutex_in_gmq_state};
	return m_inGmq; 
}
